import { editProfile,logout,setupUserProfile} from "./auth.js";
window.editProfile = editProfile;
window.logout = logout;
window.setupUserProfile = setupUserProfile;
// 全局变量声明
let currentPracticeId = null;
let questions = {
    choice: [],
    fill: [], 
    essay: []
};
let questionCounter = 0;
let blankCount = 0;
// 验证练习基本信息
 function validatePracticeInfo() {
    const practiceName = document.getElementById('practiceName')?.value.trim();
    const deadline = document.getElementById('deadline')?.value;
    const submitTimes = document.getElementById('submitTimes')?.value.trim();
    
    if (!practiceName) {
        alert('请输入练习名称');
        return false;
    }
    if(practiceName.length>25){
       alert('练习名称不能超过25字');
         return;
    }
    
    if (!deadline) {
        alert('请选择截止日期');
        return false;
    }

    
    if (submitTimes && (isNaN(parseInt(submitTimes)) || parseInt(submitTimes) <= 0)) {
        alert('提交次数必须为正整数');
        return false;
    }
    if(parseInt(submitTimes)>10){
       alert('提交次数不能超过10次');
         return;
    }

    
    return true;
}

// 显示错误信息
 function showError(message) {
    const errorContainer = document.getElementById('errorContainer');
    if (!errorContainer) {
        const container = document.createElement('div');
        container.id = 'errorContainer';
        container.className = 'error-message';
        document.body.appendChild(container);
    }
    document.getElementById('errorContainer').textContent = message;
    
    // 3秒后自动消失
    setTimeout(() => {
        document.getElementById('errorContainer').textContent = '';
    }, 3000);
}

// 暂存选择题
 function saveChoiceQuestion() {
    const questionText = document.getElementById('choiceQuestion')?.value.trim();
    const options = [
        document.getElementById('optionA')?.value.trim(),
        document.getElementById('optionB')?.value.trim(),
        document.getElementById('optionC')?.value.trim(),
        document.getElementById('optionD')?.value.trim()
    ];
    const answer = document.getElementById('correctChoice').value;
    const choiceScore = document.getElementById('choiceScore')?.value.trim();
    if (!questionText) {
        alert('请输入选择题题目内容');
        return;
    }
       if (questionText.length>100) {
        alert('题目内容不能超过100字');
        return;
    } 
    
    if (options.some(option => !option)) {
        alert('请填写所有选项内容');
        return;
    }
    if (options.some(option => option.length>100)) {
        alert('选项长度不能超过100字');
        return;
    }
    

    
    if (!answer) {
        alert('请选择正确答案');
        return;
    }
    
    if (!choiceScore) {
        alert('请设置选择题分值');
        return;


    }

    if(isNaN(parseInt(choiceScore))||parseInt(choiceScore)<=0){
        alert('分值必须为正整数');
        return;
    }

        if (parseInt(choiceScore)>100) {
        alert('选择题分值不能超过100分');
        return;


    }
    
    const question = {
        id: `q_${Date.now()}`, // 唯一ID
        type: 'choice',
        order: questionCounter++,
        data: {
            questionText,
            options,
            answer,
            score: choiceScore
        }
    };
    
    questions.choice.push(question);
    updateQuestionList();
    hideAllQuestionSections();
}

// 暂存填空题
 function saveFillQuestion() {
    const questionText = document.getElementById('fillQuestion')?.value.trim();
    const blanks = questionText.match(/__/g) || [];
    
    if (!questionText) {
        alert('请输入填空题题目内容');
        return;
    }

        if (questionText.length>200) {
        alert('题目内容不能超过200字');
        return;


    }
    
    if (blanks.length === 0) {
        alert('题目中至少需要包含一个空白处（用下划线表示）');
        return;
    }
    
    const answers = [];
    const scores = [];
    
    for (let i = 0; i < blanks.length; i++) {
        const answer = document.getElementById(`blank${i + 1}Answer`)?.value.trim();
        const score = parseInt(document.getElementById(`blank${i + 1}Score`)?.value) || 0;
        
        if (!answer) {
            alert(`请填写空${i + 1}的答案`);
            return;
        }
        if (answer.length>100) {
            alert(`空${i + 1}的答案不能超过100字`);
            return;
        }
        
        
        if (score <= 0) {
            alert(`空${i + 1}的分值必须大于0`);
            return;
        }
                if (score > 100) {
            alert(`空${i + 1}的分值必须小于100`);
            return;
        }

        answers.push(answer);
        scores.push(score);
    }
    
    const question = {
        id: `q_${Date.now()}`,
        type: 'fill',
        order: questionCounter++,
        data: {
            questionText,
            blanksCount: blanks.length,
            answers,
            scores
        }
    };
    
    questions.fill.push(question);
    updateQuestionList();
    hideAllQuestionSections();
}

// 暂存解答题
 function saveEssayQuestion() {
    const questionText = document.getElementById('essayQuestion')?.value.trim();
    const essayScore = document.getElementById('essayScore')?.value.trim();
    if (!questionText) {
        alert('请输入解答题题目内容');
        return;
    }
        if (questionText.length>200) {
        alert('解答题题目内容不能超过200字');
        return;
    }
    
    if (!essayScore) {
        alert('请设置解答题分值');
        return;
    }
        if (parseInt(essayScore)<=0||isNaN(parseInt(essayScore))) {
        alert('解答题分值必须为正整数');
        return;
    }
            if (parseInt(essayScore)>100) {
        alert('解答题分值不能超过100分');
        return;
    }
    
    const question = {
        id: `q_${Date.now()}`,
        type: 'essay',
        order: questionCounter++,
        data: {
            questionText,
            score: essayScore
        }
    };
    
    questions.essay.push(question);
    updateQuestionList();
    hideAllQuestionSections();
}

// 更新题目列表预览
 function updateQuestionList() {
    const container = document.getElementById('questionsContainer');
    container.innerHTML = '';

    const allQuestions = [...questions.choice, ...questions.fill, ...questions.essay]
       .sort((a, b) => a.order - b.order);

    if (allQuestions.length === 0) {
        container.innerHTML = `
            <p class="text-center py-8 text-blue-200/80">
                <i class="fa-solid fa-inbox text-2xl block mb-2"></i>
                暂无题目，请添加题目
            </p>`;
        return;
    }

    allQuestions.forEach((question, index) => {
        const questionCard = document.createElement('div');
        questionCard.className = 'question-card bg-gradient-to-br from-yellow-500/10 to-green-500/10 rounded-xl p-6 shadow-sm mb-6 border border-sky-400/20 hover:shadow-md transition-all';
        questionCard.dataset.id = question.id;

        let questionContent = '';
        let badgeColor = '';

        switch (question.type) {
            case 'choice':
                badgeColor = 'bg-blue-100/80 text-blue-600';
                questionContent = `
                    <div class="flex justify-between items-center mb-4">
                        <h4 class="text-lg font-bold text-white flex items-center gap-2">
                            <span class="w-6 h-6 flex items-center justify-center bg-blue-500 text-white rounded-full">${index + 1}</span>
                            选择题
                        </h4>
                        <span class="text-xs ${badgeColor} px-3 py-1 rounded-full flex items-center gap-1">
                            <i class="fa-solid fa-list-check"></i>
                            客观题
                        </span>
                    </div>
                    <div class="mb-6 bg-white/80 p-4 rounded-lg border border-blue-200/30">
                        <p class="text-gray-700 font-medium mb-4">${question.data.questionText}</p>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                            ${question.data.options.map((opt, i) => `
                                <div class="flex items-center gap-2 p-2 ${question.data.answer === String.fromCharCode(65 + i) ? 'bg-blue-100/50 rounded' : ''}">
                                    <span class="w-6 h-6 flex items-center justify-center ${question.data.answer === String.fromCharCode(65 + i) ? 'bg-blue-500 text-white' : 'bg-gray-200'} rounded-full text-xs">${String.fromCharCode(65 + i)}</span>
                                    <span>${opt}</span>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                    <div class="flex flex-wrap gap-4 text-sm">
                        <span class="bg-blue-500/20 text-blue-100 px-3 py-1 rounded-full flex items-center gap-1">
                            <i class="fa-solid fa-check-circle"></i>
                            答案：${question.data.answer}
                        </span>
                        <span class="bg-blue-500/20 text-blue-100 px-3 py-1 rounded-full flex items-center gap-1">
                            <i class="fa-solid fa-star"></i>
                            分值：${question.data.score}分
                        </span>
                    </div>
                `;
                break;

            case 'fill':
                badgeColor = 'bg-blue-100/80 text-blue-600';
                questionContent = `
                    <div class="flex justify-between items-center mb-4">
                        <h4 class="text-lg font-bold text-white flex items-center gap-2">
                            <span class="w-6 h-6 flex items-center justify-center bg-blue-500 text-white rounded-full">${index + 1}</span>
                            填空题
                        </h4>
                        <span class="text-xs ${badgeColor} px-3 py-1 rounded-full flex items-center gap-1">
                            <i class="fa-solid fa-pen-line"></i>
                            客观题
                        </span>
                    </div>
                    <div class="mb-6 bg-white/80 p-4 rounded-lg border border-blue-200/30">
                        <p class="text-gray-700 font-medium whitespace-pre-line">${question.data.questionText.replace(/__/g, '<span class="bg-yellow-100 px-1 rounded mx-0.5">____</span>')}</p>
                    </div>
                    <div class="grid grid-cols-1 md:grid-cols-${Math.min(3, question.data.blanksCount)} gap-4 mb-4">
                        ${question.data.answers.map((ans, i) => `
                            <div class="bg-white/80 p-3 rounded-lg border border-blue-200/30">
                                <div class="flex items-center gap-2 text-sm mb-1">
                                    <span class="w-5 h-5 flex items-center justify-center bg-blue-400 text-white rounded-full text-xs">${i + 1}</span>
                                    <span>填空答案</span>
                                </div>
                                <p class="text-gray-700 pl-7">${ans}</p>
                                <div class="flex items-center gap-1 text-sm mt-2 pl-7">
                                    <i class="fa-solid fa-star text-yellow-500"></i>
                                    <span>${question.data.scores[i]}分</span>
                                </div>
                            </div>
                        `).join('')}
                    </div>
                `;
                break;

            case 'essay':
                badgeColor = 'bg-amber-100/80 text-amber-600';
                questionContent = `
                    <div class="flex justify-between items-center mb-4">
                        <h4 class="text-lg font-bold text-white flex items-center gap-2">
                            <span class="w-6 h-6 flex items-center justify-center bg-amber-500 text-white rounded-full">${index + 1}</span>
                            解答题
                        </h4>
                        <span class="text-xs ${badgeColor} px-3 py-1 rounded-full flex items-center gap-1">
                            <i class="fa-solid fa-feather-pointed"></i>
                            主观题
                        </span>
                    </div>
                    <div class="mb-6 bg-white/80 p-4 rounded-lg border border-amber-200/30">
                        <p class="text-gray-700 font-medium whitespace-pre-line">${question.data.questionText}</p>
                    </div>
                    <div class="flex flex-wrap gap-4 text-sm">
                        <span class="bg-amber-500/20 text-amber-100 px-3 py-1 rounded-full flex items-center gap-1">
                            <i class="fa-solid fa-star"></i>
                            分值：${question.data.score}分
                        </span>
                    </div>
                `;
                break;
        }

        // 操作按钮区域
        const actionsHTML = `
            <div class="flex justify-end gap-3 pt-4 mt-4 border-t border-blue-400/20">
                <button class="delete-btn bg-gradient-to-r from-red-500 to-red-600 hover:from-red-600 hover:to-red-700 text-white px-4 py-1.5 rounded-lg transition-all flex items-center gap-1.5 text-sm shadow-sm hover:shadow-md">
                    <i class="fa-solid fa-trash-can"></i>
                    删除
                </button>
            </div>
        `;

        questionCard.innerHTML = questionContent + actionsHTML;
        
        // 绑定删除事件
        questionCard.querySelector('.delete-btn').addEventListener('click', () => {
            deleteQuestion(question.id);
        });

        container.appendChild(questionCard);
    });

    updateTotalScoreDisplay();
}

// 删除题目
 function deleteQuestion(id) {
    if (!confirm('确定要删除这道题目吗？')) return;
    
    questions.choice = questions.choice.filter(q => q.id !== id);
    questions.fill = questions.fill.filter(q => q.id !== id);
    questions.essay = questions.essay.filter(q => q.id !== id);
    updateTotalScoreDisplay();
    updateQuestionList();
}

// 计算总分
 function calculateTotalScore() {
    const totalQuestions = questions.choice.length + questions.fill.length + questions.essay.length;
    if(!totalQuestions) return 0;

    let total = 0;
    
    // 填空题的总分
    questions.fill.forEach(q => {
        total +=parseInt(q.data.scores.reduce((sum, score) => sum + score, 0));
    });
    //选择题总分
    questions.choice.forEach(q=>{
        total+=parseInt(q.data.score);
    });
    //解答题总分
    questions.essay.forEach(q=>{
        total+=parseInt(q.data.score);
    });
    return total;
}

// 更新总分显示
 function updateTotalScoreDisplay() {
    const totalScore = calculateTotalScore();
    const container = document.getElementById('totalScoreContainer');
    if (container) {
        container.innerHTML = `总分: ${totalScore} 分`;
    }
}

// 隐藏所有题目编辑区域
 function hideAllQuestionSections() {
    document.querySelectorAll('.question-section').forEach(section => {
        // 清空所有输入字段内容
        section.querySelectorAll('input, textarea').forEach(input => {
            input.value = '';
        });
        
        // 清空所有下拉选择框
        section.querySelectorAll('select').forEach(select => {
            select.selectedIndex = 0; // 重置为第一个选项
        });
        
        // 隐藏问题区域
        section.style.display = 'none';
    });
}

// 发布练习
document.getElementById('publishBtn').addEventListener('click', publishPractice);
 async function publishPractice() {
    // 验证基本信息
    if (!validatePracticeInfo()) return;
    
    // 验证题目数量
    const totalQuestions = questions.choice.length + questions.fill.length + questions.essay.length;
    if (totalQuestions === 0) {
        alert('请至少添加一道题目');
        return;
    }
    
    // 显示确认对话框
    const confirmMsg = `
        确认发布练习 "${document.getElementById('practiceName').value}" 吗？
        题目总数: ${totalQuestions}
        总分: ${calculateTotalScore()} 分
    `;
    if (!confirm(confirmMsg)) return;
    
    // 显示加载状态
    const publishBtn = document.getElementById('publishBtn');
    const originalText = publishBtn.textContent;
    publishBtn.disabled = true;
    publishBtn.textContent = '发布中...';
    
    try {
        // 生成练习ID
        currentPracticeId = await generateUniquePracticeId();
        const practiceName = document.getElementById('practiceName').value.trim();
        const courseCode = document.getElementById('practiceCourse').value;
        const deadline = document.getElementById('deadline').value;
        const submitTimes = document.getElementById('submitTimes').value.trim() || null;
        const startTime = new Date().toISOString().slice(0, 19).replace('T', ' ');
        const formattedDeadline = deadline + ' 23:59:59';
        //console.log(currentPracticeId, practiceName, courseCode, deadline, submitTimes, startTime, formattedDeadline);
        // 1. 创建练习
        const createResponse = await fetch('/api/create-practice', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                practice_id: currentPracticeId,
                practice_name: practiceName,
                course_code: courseCode,
                start_time: startTime,
                deadline: formattedDeadline,
                submit_times: submitTimes
            })
        });
        
        if (!createResponse.ok) {
            const result = await createResponse.json();
            throw new Error(result.message || '创建练习失败');
        }
        
        // 2. 批量添加题目
        const allQuestions = [...questions.choice, ...questions.fill, ...questions.essay]
            .sort((a, b) => a.order - b.order);
        
        let successCount = 0;
        const errors = [];
        
        // 使用Promise.allSettled处理并行请求
        const questionPromises = allQuestions.map(async (question) => {
            try {
                // 构建请求参数
                let endpoint, requestBody;
                
                switch(question.type) {
                    case 'choice':
                        // 验证选择题数据
                        if (question.data.options?.length !== 4) {
                            throw new Error('选择题必须包含4个选项');
                        }
                        
                        endpoint = '/api/add-choice-question';
                        requestBody = {
                            practice_id: currentPracticeId,
                            question_order: question.order,
                            question: question.data.questionText,
                            option_a: question.data.options[0],
                            option_b: question.data.options[1],
                            option_c: question.data.options[2],
                            option_d: question.data.options[3],
                            correct_answer: question.data.answer.toUpperCase(),
                            score: question.data.score
                        };
                        break;
                        
                    case 'fill':
                        // 验证填空题数据
                        if (!question.data.answers || !question.data.scores || 
                            question.data.answers.length !== question.data.scores.length) {
                            throw new Error('填空题答案与分数数量不匹配');
                        }
                        
                        endpoint = '/api/add-fill-question';
                        requestBody = {
                            practice_id: currentPracticeId,
                            question_order: question.order,
                            question: question.data.questionText,
                            blanks: question.data.answers.map((answer, index) => ({
                                answer: answer,
                                score: question.data.scores[index]
                            }))
                        };
                        break;
                        
                    case 'essay':
                        endpoint = '/api/add-essay-question';
                        requestBody = {
                            practice_id: currentPracticeId,
                            question_order: question.order,
                            question: question.data.questionText,
                            score: question.data.score
                        };
                        break;
                        
                    default:
                        throw new Error('未知题型');
                }
                
                // 发送请求
                const res = await fetch(endpoint, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(requestBody)
                });
                
                if (res.ok) {
                    successCount++;
                } else {
                    const errorData = await res.json();
                    throw new Error(errorData.message || '服务器错误');
                }
            } catch (error) {
                const errorMsg = `题目 ${question.order + 1} (${question.type}) 添加失败: ${error.message}`;
                console.error(errorMsg, error);
                errors.push(errorMsg);
                return Promise.reject(error);
            }
        });
        
        await Promise.allSettled(questionPromises);
        
        // 3. 显示结果
        if (successCount === totalQuestions) {
            alert(`✅ 练习发布成功，共添加 ${successCount} 道题目`);
            resetPracticeForm();
        } else {
            let errorMsg = `⚠️ 部分题目添加失败 (成功 ${successCount}/${totalQuestions}),练习发布终止\n\n`;
            errorMsg += errors.join('\n');
            await fetch(`/api/practice/${currentPracticeId}`, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            alert(errorMsg);
        }
    } catch (error) {
        console.error('发布练习失败:', error);
        alert(`发布失败: ${error.message}`);
    } finally {
        // 恢复按钮状态
        publishBtn.disabled = false;
        publishBtn.textContent = originalText;
    }
}

// 重置表单
 function resetPracticeForm() {
    document.getElementById('practiceName').value = '';
    document.getElementById('practiceCourse').value = '';
    document.getElementById('deadline').value = '';
    document.getElementById('submitTimes').value = '';
    document.getElementById('questionsContainer').innerHTML = '<p class="empty-questions">暂无题目，请添加题目</p>';
    
    questions = {
        choice: [],
        fill: [], 
        essay: []
    };
    
    questionCounter = 0;
    updateTotalScoreDisplay();
}

// 生成随机字符串
 async function generateRandomString(length) {
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let result = '';
    for (let i = 0; i < length; i++) {
        result += characters.charAt(Math.floor(Math.random() * characters.length));
    }
    return result;
}

 async function generateUniquePracticeId() {
    let practiceId;
    let isUnique = false;
    while (!isUnique) {
        practiceId = generateRandomString(50);
        const response = await fetch(`/practice/exists/${practiceId}`);
        const checkData = await response.json();
        if (!checkData.exists) {
            isUnique = true;
        }
    }
    return practiceId;
}

// 页面加载后初始化
 document.addEventListener('DOMContentLoaded', () => {
    // 初始化题目列表
    updateQuestionList();
    
    // 初始化题目添加按钮事件
    document.getElementById('addChoiceBtn').addEventListener('click', () => {
        hideAllQuestionSections();
        document.getElementById('choiceQuestionSection').style.display = 'block';
    });
    
    document.getElementById('addFillBtn').addEventListener('click', () => {
        hideAllQuestionSections();
        document.getElementById('fillQuestionSection').style.display = 'block';
        blankCount = 0;
        document.getElementById('blankAnswers').innerHTML = '';
    });
    
    document.getElementById('addEssayBtn').addEventListener('click', () => {
        hideAllQuestionSections();
        document.getElementById('essayQuestionSection').style.display = 'block';
    });
    
    // 取消按钮事件
    document.querySelectorAll('.cancel-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            hideAllQuestionSections();
        });
    });
    
    // 自动识别填空题中的空
    document.getElementById('fillQuestion').addEventListener('input', (e) => {
        const text = e.target.value;
        const blanks = text.match(/__/g) || [];
        blankCount = blanks.length;
        
        // 更新空白区域
        const blankAnswers = document.getElementById('blankAnswers');
        blankAnswers.innerHTML = '';
        
        if (blankCount > 3) {
            alert('题目中最多只能有3个空');
            return;
        }
        
        blanks.forEach((_, index) => {
            const blankDiv = document.createElement('div');
            blankDiv.className = 'form-group blank-group';
            blankDiv.innerHTML = `
<div class="blank-answer-item bg-white/80 p-4 rounded-lg border border-gray-200/70 shadow-sm hover:shadow transition-all">
    <div class="flex flex-col md:flex-row gap-4 items-end">
        <div class="form-group flex-1 w-full">
            <label class="block text-sm font-medium text-gray-600 mb-2 flex items-center">
                <span class="w-6 h-6 flex items-center justify-center bg-amber-500 text-white rounded-full mr-2 text-xs">${index + 1}</span>
                填空答案：
            </label>
            <input type="text" id="blank${index + 1}Answer" 
                   class="w-full px-4 py-2.5 border border-gray-200 rounded-lg focus:ring-2 focus:ring-amber-200 focus:border-amber-400 outline-none transition-all hover:border-gray-300">
        </div>
        <div class="form-group md:w-32">
            <label class="block text-sm font-medium text-gray-600 mb-2 flex items-center">
                <i class="fa-solid fa-star text-gray-400 mr-2 text-[0.9em]"></i>
                分值：
            </label>
            <div class="relative">
                <input type="number" id="blank${index + 1}Score" min="1" value="1"
                       class="w-full pl-9 pr-4 py-2.5 border border-gray-200 rounded-lg focus:ring-2 focus:ring-amber-200 focus:border-amber-400 outline-none transition-all hover:border-gray-300">
                <span class="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-500"></span>
            </div>
        </div>
    </div>
</div>
`;
            blankAnswers.appendChild(blankDiv);
        });
    });
    
    // 导入帮助按钮事件 - 使用弹出窗口
    document.getElementById('importHelpBtn').addEventListener('click', () => {
        const helpWindow = window.open('', 'importHelp', 
            'width=800,height=600,top=100,left=100');
        helpWindow.document.write(`
            <!DOCTYPE html>
            <html>
            <head>
                <title>导入帮助</title>
                <style>
                    body { font-family: Arial; padding: 20px; }
                    .help-item { margin: 20px 0; }
                    img { max-width: 100%; border: 1px solid #ddd; }
                </style>
            </head>
            <body>
                <h3>导入题目帮助</h3>
                <div class="help-item">
                    <p>选择题导入示例：</p>
                    <img src="images/import_choice_help.png" alt="选择题导入示例">
                    <p>请按照示例格式准备Excel文件中的选择题</p>
                </div>
                <div class="help-item">
                    <p>填空题导入示例：</p>
                    <img src="images/import_fill_help.png" alt="填空题导入示例">
                    <p>请按照示例格式准备Excel文件中的填空题</p>
                </div>
                <div class="help-item">
                    <p>解答题导入示例：</p>
                    <img src="images/import_essay_help.png" alt="解答题导入示例">
                    <p>请按照示例格式准备Excel文件中的解答题</p>
                </div>
                <button onclick="window.close()">关闭</button>
            </body>
            </html>
        `);
    });

    // 返回按钮事件
    document.getElementById('backBtn').addEventListener('click', () => {
        window.location.href ='success.html'+window.location.search;
    });
    
    // 截止时间验证
    document.getElementById('deadline').addEventListener('change', validateDeadline);
});

// 验证截止时间
 function validateDeadline() {
    const deadline = document.getElementById('deadline').value;
    if (!deadline) return;
    
    const today = new Date();
    const selectedDate = new Date(deadline);
    
    // 设置今天的时间为00:00:00
    today.setHours(0, 0, 0, 0);
    
    if (selectedDate < today) {
        alert('截止日期不能早于今天');
        document.getElementById('deadline').value = '';
    }
}

 async function getCurrentTeacherId() {
    try {
        const urlParams = new URLSearchParams(window.location.search);
        const username = urlParams.get('username');
        if (!username) {
            throw new Error('URL中缺少username参数');
        }
        
        const response = await fetch(`/user-info?username=${username}`);
        if (!response.ok) {
            throw new Error(`HTTP错误: ${response.status}`);
        }
        
        const data = await response.json();
        if (data.role !== '教师') {
            throw new Error('当前用户不是教师');
        }
        
        return data.user_id;
    } catch (error) {
        console.error('获取教师ID失败:', error);
        throw error;
    }
}

// 页面加载完成后获取教师对应的课程
window.onload = async function() {
    try {
        const urlParams = new URLSearchParams(window.location.search);
        const username = urlParams.get('username');
        await setupUserProfile(username);
        if (!username) {
            throw new Error('URL中缺少username参数');
        }

        const response = await fetch('/get-my-courses', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ username })
        });

        if (!response.ok) {
            throw new Error(`HTTP错误: ${response.status}`);
        }

        const courses = await response.json();
        const courseSelect = document.getElementById('practiceCourse');
        courses.forEach(course => {
            const option = document.createElement('option');
            option.value = course.course_code;
            option.textContent = course.course_name;
            courseSelect.appendChild(option);
        });
    } catch (error) {
        console.error('获取课程失败:', error);
    }
};

// 导入题目函数 - 修改为调用后端 API
document.getElementById('confirmPracticeImport').addEventListener('click', async () => {
    const fileInput = document.getElementById('importPracticeFile');
    const file = fileInput.files[0];
    //console.log(file);
    if (!file) {
        alert('请选择要导入的文件');
        return;
    }

    if (!file.name.endsWith('.xlsx')) {
        alert('仅支持.xlsx格式的Excel文件');
        return;
    }

    try {
        // 显示加载状态
        const loadingIndicator = document.getElementById('importPracticeLoading');
        if (loadingIndicator) loadingIndicator.style.display = 'block';

        // 创建表单数据
        const formData = new FormData();
        formData.append('practice_id',currentPracticeId);
        formData.append('importFile', file);
        //console.log('FormData 包含的字段:', [...formData.keys()]);
        // 调用后端API
        const response = await fetch('/api/import-practice', {
            method: 'POST',
            body: formData
        });

        //console.log('响应状态:', response.status);

        if (!response.ok) {
            const errorData = await response.json();
            console.log('响应错误内容:', errorData);
            throw new Error(errorData.message || '服务器错误');
        }

        const result = await response.json();
        // 将导入的题目添加到全局questions数组
        result.questions.choice.forEach(q => {
            questions.choice.push({
                id: `q_${Date.now()}_${Math.floor(Math.random() * 1000)}`, // 增强ID唯一性
                type: 'choice',
                order: questionCounter++,
                data: {
                    questionText: q.questionText,
                    options: q.options,
                    answer: q.answer,
                    score: q.score
                }
            });
        });

        result.questions.fill.forEach(q => {
            questions.fill.push({
                id: `q_${Date.now()}_${Math.floor(Math.random() * 1000)}`,
                type: 'fill',
                order: questionCounter++,
                data: {
                    questionText: q.questionText,
                    blanksCount: q.blanksCount,
                    answers: q.answers,
                    scores: q.scores
                }
            });
        });

        result.questions.essay.forEach(q => {
            questions.essay.push({
                id: `q_${Date.now()}_${Math.floor(Math.random() * 1000)}`,
                type: 'essay',
                order: questionCounter++,
                data: {
                    questionText: q.questionText,
                    score: q.score
                }
            });
        });

        // 更新题目列表和总分
        updateQuestionList();
        
        alert(`成功导入${result.totalCount}道题目\n
              选择题：${result.choiceCount}道\n
              填空题：${result.fillCount}道\n
              解答题：${result.essayCount}道`);
        //导入成功后自动关闭模态框
        const modal = document.getElementById('importPracticeModal');
        modal.style.opacity = '0';
        modal.style.pointerEvents = 'none';
    } catch (error) {
        console.error('导入题目失败:', error);
        showError(error.message || '导入题目失败，请重试');
    } finally {
        // 隐藏加载状态
        const loadingIndicator = document.getElementById('importPracticeLoading');
        if (loadingIndicator) loadingIndicator.style.display = 'none';
    }
});


// 打开导入题目模态框

document.getElementById('importBtn').addEventListener('click', function() {
    //console.log('打开导入题目模态框');
    const modal = document.getElementById('importPracticeModal');
    modal.classList.remove('opacity-0', 'pointer-events-none');
    modal.querySelector('.dialog-content').classList.remove('scale-95');
    modal.querySelector('.dialog-content').classList.add('scale-100');
});
document.getElementById('cancelPracticeImport').addEventListener('click',function() {
    const modal = document.getElementById('importPracticeModal');
    modal.classList.add('opacity-0', 'pointer-events-none');
    modal.querySelector('.dialog-content').classList.add('scale-95');
    modal.querySelector('.dialog-content').classList.remove('scale-100');
});
document.getElementById('closeImportPracticeModalBtn').addEventListener('click',function() {
    const modal = document.getElementById('importPracticeModal');
    modal.classList.add('opacity-0', 'pointer-events-none');
    modal.querySelector('.dialog-content').classList.add('scale-95');
    modal.querySelector('.dialog-content').classList.remove('scale-100');;
});

document.getElementById('submitChoiceBtn').addEventListener('click',saveChoiceQuestion);
document.getElementById('submitFillBtn').addEventListener('click',saveFillQuestion);
document.getElementById('submitEssayBtn').addEventListener('click',saveEssayQuestion);
document.getElementById('canceladdChoiceBtn').addEventListener('click',hideAllQuestionSections);
document.getElementById('canceladdFillBtn').addEventListener('click',hideAllQuestionSections);
document.getElementById('canceladdEssayBtn').addEventListener('click',hideAllQuestionSections);

// 为查看已有练习按钮添加绑定事件
document.getElementById('viewPracticeBtn').addEventListener('click', async () => {
    window.location.href = 'view-practice.html' + window.location.search;
});

//为批改练习按钮添加绑定事件
document.getElementById('gradePracticeBtn').addEventListener('click', async () => {
    window.location.href = 'grade-practice.html' + window.location.search;
});

document.addEventListener('DOMContentLoaded', function() {
    // 获取"返回"链接元素
    const backLink = document.querySelector('ul.flex li:first-child a');
    if (backLink) {
        // 添加点击事件监听器
        backLink.addEventListener('click', function(event) {
            event.preventDefault(); 
            window.location.href ='success.html'+window.location.search;
        });
    }
});

 function escapeHTML(str) {
    if (typeof str !== 'string') return str;
    return str.replace(/[&<>"']/g, function (match) {
        switch (match) {
            case '&':
                return '&amp;';
            case '<':
                return '&lt;';
            case '>':
                return '&gt;';
            case '"':
                return '&quot;';
            case "'":
                return '&#039;';
        }
    });
}


export 
{
 validatePracticeInfo,
      showError ,
      saveChoiceQuestion ,
      saveFillQuestion,
      saveEssayQuestion,
      updateQuestionList ,
      deleteQuestion ,
      calculateTotalScore ,
      hideAllQuestionSections,
      publishPractice ,
      escapeHTML ,
}
     